<template>
  <div class="merchant-profile min-h-screen bg-gray-50 dark:bg-gray-900">
    <!-- 页面头部 -->
    <div
      class="profile-header bg-white dark:bg-gray-800 shadow-sm relative w-full"
    >
      <!-- 用户信息容器 -->
      <div class="container mx-auto px-4 py-4 relative max-w-7xl w-full">
        <div class="header-content relative rounded-lg overflow-hidden">
          <div
            class="header-bg bg-cover bg-center"
            :style="{
              backgroundImage: `url(${userInfo.coverImage || '/images/default-cover.jpg'})`,
            }"
          ></div>

          <!-- 操作按钮组 -->
          <div
            class="absolute right-4 top-4 flex flex-col items-end space-y-4 z-20"
          >
            <a-button-group>
              <a-tooltip content="重置修改">
                <a-button
                  @click="resetForm"
                  class="btn-action hover:scale-105 transform transition-all"
                >
                  <template #icon>
                    <icon-refresh />
                  </template>
                  重置
                </a-button>
              </a-tooltip>

              <a-tooltip content="保存修改">
                <a-button
                  type="primary"
                  class="btn-action hover:scale-105 transform transition-all"
                  @click="handleSubmit"
                >
                  <template #icon>
                    <icon-check />
                  </template>
                  保存修改
                </a-button>
              </a-tooltip>
            </a-button-group>

            <a-tooltip content="更换封面图片">
              <a-button
                type="outline"
                class="btn-cover hover:scale-105 transform transition-all duration-300"
                @click="handleUpdateCover"
              >
                <template #icon>
                  <icon-upload />
                </template>
                更换封面
              </a-button>
            </a-tooltip>
          </div>

          <div class="flex flex-wrap items-center relative z-10 px-6 py-4">
            <div class="relative group">
              <a-avatar
                :size="100"
                :image-url="userInfo.avatar"
                class="ring-4 ring-white dark:ring-gray-800 shadow-lg transform group-hover:scale-105 transition-transform duration-300"
              />
              <div
                class="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-300"
              >
                <a-button
                  type="primary"
                  shape="circle"
                  class="update-avatar-btn"
                  @click="handleUpdateAvatar"
                >
                  <template #icon>
                    <icon-camera />
                  </template>
                </a-button>
              </div>
            </div>
            <div class="ml-4 flex-1">
              <h1 class="text-2xl font-bold text-white mb-1 drop-shadow-md">
                {{ userInfo.storeName }}
              </h1>
              <p class="text-gray-200 drop-shadow">{{ userInfo.username }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="container mx-auto px-4 py-8 max-w-7xl">
      <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <!-- 左侧：基本信息 -->
        <div class="lg:col-span-2 space-y-6">
          <a-card>
            <template #title>
              <div class="flex items-center">
                <icon-user class="mr-2" />
                <span class="text-lg font-medium">基本信息</span>
              </div>
            </template>

            <a-form
              ref="formRef"
              :model="userInfo"
              :rules="rules"
              layout="vertical"
              class="max-w-3xl"
            >
              <a-form-item
                field="storeName"
                label="店铺名称"
                :rules="[{ required: true, message: '请输入店铺名称' }]"
              >
                <a-input
                  v-model="userInfo.storeName"
                  placeholder="请输入店铺名称"
                >
                  <template #prefix>
                    <icon-shop />
                  </template>
                </a-input>
              </a-form-item>

              <a-form-item
                field="phone"
                label="联系电话"
                :rules="[{ required: true, message: '请输入联系电话' }]"
              >
                <a-input v-model="userInfo.phone" placeholder="请输入联系电话">
                  <template #prefix>
                    <icon-phone />
                  </template>
                </a-input>
              </a-form-item>

              <a-form-item
                field="email"
                label="电子邮箱"
                :rules="[{ required: true, message: '请输入电子邮箱' }]"
              >
                <a-input v-model="userInfo.email" placeholder="请输入电子邮箱">
                  <template #prefix>
                    <icon-email />
                  </template>
                </a-input>
              </a-form-item>

              <a-form-item
                field="location"
                label="所在地区"
                :rules="[{ required: true, message: '请选择所在地区' }]"
              >
                <a-cascader
                  v-model="userInfo.location"
                  :options="locationOptions"
                  placeholder="请选择所在地区"
                />
              </a-form-item>

              <a-form-item
                field="address"
                label="详细地址"
                :rules="[{ required: true, message: '请输入详细地址' }]"
              >
                <a-input
                  v-model="userInfo.address"
                  placeholder="请输入详细地址"
                >
                  <template #prefix>
                    <icon-location />
                  </template>
                </a-input>
              </a-form-item>

              <a-form-item field="bio" label="店铺简介">
                <a-textarea
                  v-model="userInfo.bio"
                  :max-length="500"
                  show-word-limit
                  placeholder="介绍一下你的店铺特色..."
                />
              </a-form-item>

              <a-form-item field="tags" label="店铺标签">
                <a-select
                  v-model="userInfo.tags"
                  multiple
                  allow-create
                  allow-search
                  placeholder="请选择或输入标签"
                >
                  <a-option v-for="tag in tagOptions" :key="tag" :value="tag">
                    {{ tag }}
                  </a-option>
                </a-select>
              </a-form-item>
            </a-form>
          </a-card>

          <a-card>
            <template #title>
              <div class="flex items-center justify-between">
                <div class="flex items-center">
                  <icon-image class="mr-2" />
                  <span class="text-lg font-medium">店铺图片</span>
                </div>
                <a-button type="primary" @click="handleAddImages">
                  <template #icon>
                    <icon-plus />
                  </template>
                  添加图片
                </a-button>
              </div>
            </template>

            <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
              <div
                v-for="(image, index) in userInfo.images"
                :key="index"
                class="relative group"
              >
                <a-image
                  :src="image.url"
                  fit="cover"
                  class="w-full aspect-square rounded-lg"
                />
                <div
                  class="absolute inset-0 bg-black bg-opacity-50 opacity-0 group-hover:opacity-100 transition-opacity duration-300 flex items-center justify-center rounded-lg"
                >
                  <a-button
                    status="danger"
                    shape="circle"
                    @click="handleRemoveImage(index)"
                  >
                    <template #icon>
                      <icon-delete />
                    </template>
                  </a-button>
                </div>
              </div>
            </div>
          </a-card>
        </div>

        <!-- 右侧：账号信息和数据统计 -->
        <div class="space-y-6">
          <!-- 账号信息卡片 -->
          <a-card>
            <template #title>
              <div class="flex items-center">
                <icon-info-circle class="mr-2" />
                <span class="text-lg font-medium">账号信息</span>
              </div>
            </template>

            <div class="space-y-4">
              <div class="p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
                <div class="text-sm text-gray-500 dark:text-gray-400">
                  账号ID
                </div>
                <div class="mt-1 font-medium">{{ userInfo.id }}</div>
              </div>

              <div class="p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
                <div class="text-sm text-gray-500 dark:text-gray-400">
                  账号创建时间
                </div>
                <div class="mt-1 font-medium">
                  {{ formatDate(userInfo.createTime) }}
                </div>
              </div>

              <div class="p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
                <div class="text-sm text-gray-500 dark:text-gray-400">
                  最后登录时间
                </div>
                <div class="mt-1 font-medium">
                  {{ formatDate(userInfo.lastLoginTime) }}
                </div>
              </div>

              <div class="p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
                <div class="text-sm text-gray-500 dark:text-gray-400">
                  账号状态
                </div>
                <div class="mt-1">
                  <a-tag
                    :color="userInfo.status === 'active' ? 'green' : 'red'"
                  >
                    {{ userInfo.status === "active" ? "正常" : "已禁用" }}
                  </a-tag>
                </div>
              </div>
            </div>
          </a-card>

          <!-- 数据统计卡片 -->
          <a-card>
            <template #title>
              <div class="flex items-center">
                <icon-bar-chart class="mr-2" />
                <span class="text-lg font-medium">数据统计</span>
              </div>
            </template>

            <div class="grid grid-cols-2 gap-4">
              <div
                class="text-center p-4 bg-gray-50 dark:bg-gray-700 rounded-lg"
              >
                <div class="text-2xl font-bold text-primary-500">
                  {{ statistics.orderCount }}
                </div>
                <div class="text-sm text-gray-500 dark:text-gray-400 mt-1">
                  总订单数
                </div>
              </div>

              <div
                class="text-center p-4 bg-gray-50 dark:bg-gray-700 rounded-lg"
              >
                <div class="text-2xl font-bold text-primary-500">
                  {{ statistics.productCount }}
                </div>
                <div class="text-sm text-gray-500 dark:text-gray-400 mt-1">
                  商品数量
                </div>
              </div>

              <div
                class="text-center p-4 bg-gray-50 dark:bg-gray-700 rounded-lg"
              >
                <div class="text-2xl font-bold text-primary-500">
                  {{ statistics.reviewCount }}
                </div>
                <div class="text-sm text-gray-500 dark:text-gray-400 mt-1">
                  评价数量
                </div>
              </div>

              <div
                class="text-center p-4 bg-gray-50 dark:bg-gray-700 rounded-lg"
              >
                <div class="text-2xl font-bold text-primary-500">
                  {{ statistics.rating }}
                </div>
                <div class="text-sm text-gray-500 dark:text-gray-400 mt-1">
                  平均评分
                </div>
              </div>
            </div>
          </a-card>

          <!-- 认证信息卡片 -->
          <a-card>
            <template #title>
              <div class="flex items-center">
                <icon-check-circle class="mr-2" />
                <span class="text-lg font-medium">认证信息</span>
              </div>
            </template>

            <div class="space-y-4">
              <div
                class="flex items-center justify-between p-4 bg-gray-50 dark:bg-gray-700 rounded-lg"
              >
                <div>
                  <div class="font-medium">实名认证</div>
                  <div class="text-sm text-gray-500 dark:text-gray-400 mt-1">
                    已完成身份认证
                  </div>
                </div>
                <a-tag color="green">已认证</a-tag>
              </div>

              <div
                class="flex items-center justify-between p-4 bg-gray-50 dark:bg-gray-700 rounded-lg"
              >
                <div>
                  <div class="font-medium">营业执照</div>
                  <div class="text-sm text-gray-500 dark:text-gray-400 mt-1">
                    已上传营业执照
                  </div>
                </div>
                <a-tag color="green">已认证</a-tag>
              </div>

              <div
                class="flex items-center justify-between p-4 bg-gray-50 dark:bg-gray-700 rounded-lg"
              >
                <div>
                  <div class="font-medium">经营许可</div>
                  <div class="text-sm text-gray-500 dark:text-gray-400 mt-1">
                    已上传相关证件
                  </div>
                </div>
                <a-tag color="green">已认证</a-tag>
              </div>
            </div>
          </a-card>
        </div>
      </div>
    </div>

    <!-- 头像上传对话框 -->
    <a-modal
      v-model:visible="avatarDialogVisible"
      title="更换头像"
      @ok="confirmUpdateAvatar"
      @cancel="avatarDialogVisible = false"
    >
      <a-upload
        class="avatar-uploader"
        action="/api/upload"
        :show-file-list="false"
        :before-upload="beforeAvatarUpload"
        @change="handleAvatarSuccess"
      >
        <img v-if="tempAvatar" :src="tempAvatar" class="avatar-preview" />
        <div v-else class="avatar-uploader-icon">
          <icon-plus />
        </div>
      </a-upload>
    </a-modal>

    <!-- 图片上传对话框 -->
    <a-modal
      v-model:visible="imageDialogVisible"
      title="添加店铺图片"
      @ok="confirmAddImages"
      @cancel="imageDialogVisible = false"
    >
      <a-upload
        class="image-uploader"
        action="/api/upload"
        list-type="picture-card"
        :multiple="true"
        :limit="9"
        @change="handleImageSuccess"
      >
        <template #upload-button>
          <div>
            <icon-plus />
            <div class="mt-1">上传图片</div>
          </div>
        </template>
      </a-upload>
    </a-modal>

    <!-- 使用全局图片编辑组件 -->
    <ImageEditor
      v-model:visible="coverEditorVisible"
      :title="'编辑封面图片'"
      :upload-action="'/api/upload/cover'"
      :aspect-ratio="4"
      @success="handleCoverConfirm"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { Message } from "@arco-design/web-vue";
import {
  IconUser,
  IconShop,
  IconPhone,
  IconEmail,
  IconLocation,
  IconCamera,
  IconUpload,
  IconImage,
  IconPlus,
  IconDelete,
  IconInfoCircle,
  IconBarChart,
  IconCheckCircle,
  IconRefresh,
  IconCheck,
} from "@arco-design/web-vue/es/icon";
import ImageEditor from "@/components/common/ImageEditor.vue";
import { useUserStore } from "@/stores/user";

const userStore = useUserStore();
const formRef = ref(null);
const avatarDialogVisible = ref(false);
const imageDialogVisible = ref(false);
const tempAvatar = ref("");
const coverEditorVisible = ref(false);

const userInfo = ref({
  id: "MC10086",
  username: "",
  storeName: "",
  avatar: "",
  coverImage: "",
  phone: "",
  email: "",
  bio: "",
  location: [],
  address: "",
  tags: [],
  images: [],
  createTime: "",
  lastLoginTime: "",
  status: "active",
});

const statistics = ref({
  orderCount: 286,
  productCount: 68,
  reviewCount: 126,
  rating: 4.8,
});

const locationOptions = [
  {
    value: "guangxi",
    label: "广西",
    children: [
      {
        value: "guigang",
        label: "贵港",
        children: [
          { value: "gangbei", label: "港北区" },
          { value: "gangnan", label: "港南区" },
          { value: "qintang", label: "覃塘区" },
          { value: "guiping", label: "桂平市" },
          { value: "pingnan", label: "平南县" },
        ],
      },
    ],
  },
];

const tagOptions = [
  "文创产品",
  "手工艺品",
  "特色商品",
  "文化创意",
  "传统工艺",
  "现代设计",
  "本地特产",
  "文化IP",
  "创意礼品",
  "艺术收藏",
];

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    // TODO: 调用获取用户信息的 API
    // const { data } = await getUserInfo()
    // userInfo.value = data

    // 模拟数据
    userInfo.value = {
      ...userInfo.value,
      username: "merchant_admin",
      storeName: "贵港文创馆",
      avatar: "https://placeholder.co/400",
      coverImage: "https://placeholder.co/1920x400",
      phone: "13800138000",
      email: "merchant@example.com",
      bio: "贵港市最具特色的文创产品店铺，提供优质的文化创意产品。",
      location: ["guangxi", "guigang", "gangbei"],
      address: "贵港市港北区文化创意园A区101号",
      tags: ["文创产品", "手工艺品", "特色商品", "文化创意"],
      images: [
        { url: "https://placeholder.co/400" },
        { url: "https://placeholder.co/400" },
        { url: "https://placeholder.co/400" },
        { url: "https://placeholder.co/400" },
      ],
      createTime: "2023-01-01 12:00:00",
      lastLoginTime: "2024-03-15 15:30:00",
    };
  } catch (error) {
    Message.error("获取用户信息失败");
  }
};

// 更新头像
const handleUpdateAvatar = () => {
  avatarDialogVisible.value = true;
};

// 更新封面
const handleUpdateCover = () => {
  coverEditorVisible.value = true;
};

// 封面图片编辑确认
const handleCoverConfirm = async (result) => {
  try {
    const { url } = result;
    userInfo.value.coverImage = url;
    Message.success("封面更新成功");
  } catch (error) {
    Message.error("封面更新失败");
  }
};

// 头像上传前的验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === "image/jpeg";
  const isPNG = file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    Message.error("头像图片只能是 JPG 或 PNG 格式!");
    return false;
  }
  if (!isLt2M) {
    Message.error("头像图片大小不能超过 2MB!");
    return false;
  }
  return true;
};

// 头像上传成功
const handleAvatarSuccess = (info) => {
  if (info.file.status === "done") {
    tempAvatar.value = URL.createObjectURL(info.file.originFile);
  }
};

// 确认更新头像
const confirmUpdateAvatar = () => {
  if (tempAvatar.value) {
    userInfo.value.avatar = tempAvatar.value;
    avatarDialogVisible.value = false;
    Message.success("头像更新成功");
  }
};

// 添加店铺图片
const handleAddImages = () => {
  imageDialogVisible.value = true;
};

// 图片上传成功
const handleImageSuccess = (info) => {
  if (info.file.status === "done") {
    userInfo.value.images.push({
      url: URL.createObjectURL(info.file.originFile),
    });
  }
};

// 确认添加图片
const confirmAddImages = () => {
  imageDialogVisible.value = false;
  Message.success("图片添加成功");
};

// 删除图片
const handleRemoveImage = (index) => {
  userInfo.value.images.splice(index, 1);
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    // TODO: 调用更新用户信息的 API
    // await updateUserInfo(userInfo.value)
    Message.success("保存成功");
  } catch (error) {
    Message.error("保存失败");
  }
};

// 重置表单
const resetForm = () => {
  if (!formRef.value) return;
  formRef.value.resetFields();
};

// 格式化日期
const formatDate = (date) => {
  if (!date) return "暂无";
  return new Date(date).toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  });
};

onMounted(() => {
  fetchUserInfo();
});
</script>

<style lang="scss" scoped>
.merchant-profile {
  .profile-header {
    position: relative;
    overflow: hidden;
    margin: 16px auto;
    width: 100%;
    max-width: 1280px;
    padding: 0;
  }

  .header-content {
    margin: 0 24px;
    background-color: var(--color-bg-2);
    box-shadow: var(--shadow-1);
  }

  .header-bg {
    position: absolute;
    inset: 0;
    height: 160px;
    background-color: var(--color-fill-2);
    transition: all 0.3s ease;
    filter: brightness(0.8);
    z-index: 1;
  }

  .header-bg::after {
    content: "";
    position: absolute;
    inset: 0;
    background: linear-gradient(
      to bottom,
      rgba(0, 0, 0, 0.3),
      rgba(0, 0, 0, 0.5)
    );
    z-index: 2;
  }

  @media (max-width: 1320px) {
    .profile-header {
      margin: 16px;
      width: calc(100% - 32px);
    }

    .header-content {
      margin: 0 16px;
    }
  }

  @media (max-width: 768px) {
    .profile-header {
      margin: 12px;
      width: calc(100% - 24px);
    }

    .header-content {
      margin: 0 12px;
    }

    .profile-header .flex-wrap {
      flex-direction: column;
      text-align: center;
    }

    .profile-header .ml-4 {
      margin-left: 0;
      margin-top: 1rem;
    }

    .profile-header .absolute.right-4 {
      right: 0.75rem;
    }
  }

  @media (max-width: 480px) {
    .profile-header {
      margin: 8px;
      width: calc(100% - 16px);
    }

    .header-content {
      margin: 0 8px;
    }

    .header-bg {
      height: 140px;
    }

    .profile-header :deep(.arco-avatar) {
      width: 80px !important;
      height: 80px !important;
    }

    .profile-header .text-2xl {
      font-size: 1.5rem;
    }
  }

  /* 按钮样式优化 */
  .btn-action,
  .btn-cover {
    position: relative;
    z-index: 20;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
    backdrop-filter: blur(8px);
    transition: all 0.3s ease;
  }

  .btn-action:hover {
    box-shadow:
      0 4px 6px -1px rgba(0, 0, 0, 0.1),
      0 2px 4px -1px rgba(0, 0, 0, 0.06);
  }

  .btn-cover {
    background-color: rgba(255, 255, 255, 0.1);
    border-color: rgba(255, 255, 255, 0.2);
    color: white;

    &:hover {
      background-color: rgba(255, 255, 255, 0.2);
      border-color: rgba(255, 255, 255, 0.3);
      box-shadow:
        0 4px 6px -1px rgba(0, 0, 0, 0.1),
        0 2px 4px -1px rgba(0, 0, 0, 0.06);
    }
  }

  .update-avatar-btn {
    background-color: rgba(0, 0, 0, 0.6);
    border: none;
  }

  .avatar-uploader {
    text-align: center;

    :deep(.arco-upload) {
      width: 178px;
      height: 178px;
      border: 1px dashed var(--color-border);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--transition-duration-1);

      &:hover {
        border-color: rgb(var(--primary-6));
      }
    }

    .avatar-uploader-icon {
      font-size: 28px;
      color: rgb(var(--gray-6));
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }

    .avatar-preview {
      width: 178px;
      height: 178px;
      display: block;
    }
  }

  .image-uploader {
    :deep(.arco-upload-picture-card) {
      width: 100px;
      height: 100px;
    }
  }

  .text-primary-500 {
    color: rgb(var(--primary-6));
  }

  :deep(.arco-card) {
    background-color: var(--color-bg-2);
    border-color: var(--color-border);
  }

  :deep(.arco-input-wrapper) {
    background-color: var(--color-bg-2);
    border-color: var(--color-border);
  }

  :deep(.arco-select-view) {
    background-color: var(--color-bg-2);
  }

  :deep(.arco-tag) {
    background-color: var(--color-bg-2);
  }
}
</style>
